//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-station.cm"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 8
#property indicator_minimum 0
#property indicator_maximum 5
#property strict

//
//
//
//
//

enum enTimeFrames
{
   tf_cu  = PERIOD_CURRENT, // Current time frame
   tf_m1  = PERIOD_M1,      // 1 minute
   tf_m5  = PERIOD_M5,      // 5 minutes
   tf_m15 = PERIOD_M15,     // 15 minutes
   tf_m30 = PERIOD_M30,     // 30 minutes
   tf_h1  = PERIOD_H1,      // 1 hour
   tf_h4  = PERIOD_H4,      // 4 hours
   tf_d1  = PERIOD_D1,      // Daily
   tf_w1  = PERIOD_W1,      // Weekly
   tf_mn1 = PERIOD_MN1,     // Monthly
   tf_n1  = -1,             // First higher time frame
   tf_n2  = -2,             // Second higher time frame
   tf_n3  = -3              // Third higher time frame
};

extern enTimeFrames TimeFrame1            = tf_cu;                       // First time frame
extern enTimeFrames TimeFrame2            = tf_n1;                       // Second time frame
extern enTimeFrames TimeFrame3            = tf_n2;                       // Third time frame
extern enTimeFrames TimeFrame4            = tf_n3;                       // Fourth time frame
extern int          SlowLength            = 7;                           // Slow length
extern double       SlowPipDisplace       = 0;                           // Slow pip displace
extern int          FastLength            = 3;                           // Fast length
extern double       FastPipDisplace       = 0;                           // Fast pip displace
extern string       UniqueID              = "4 Time frame ptl";          // Unique ID
extern bool         alertsOn              = false;                       // Turn alerts on?
extern int          alertsLevel           = 3;                           // Alerts level
extern bool         alertsMessage         = false;                       // Alerts message?
extern bool         alertsSound           = false;                       // Alerts sound?
extern bool         alertsEmail           = false;                       // Alerts email?
extern int          LinesWidth            = 0;                           // Lines width
extern color        LabelsColor           = clrDarkGray;                 // Lines color
extern int          LabelsHorizontalShift = 5;                           // Labels horizontal shift
extern double       LabelsVerticalShift   = 1.5;                         // Labels vertical shift
extern color        ColorUp               = clrDodgerBlue;               // Color for up
extern color        ColorDown             = clrSandyBrown;               // Color for down

double bb1u[],bb1d[],bb2u[],bb2d[],bb3u[],bb3d[],bb4u[],bb4d[],count[];

int    timeFrames[4];
bool   returnBars;
bool   calculateValue;
string indicatorFileName;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   SetIndexBuffer(0,bb1u);
   SetIndexBuffer(1,bb1d);
   SetIndexBuffer(2,bb2u);
   SetIndexBuffer(3,bb2d);
   SetIndexBuffer(4,bb3u);
   SetIndexBuffer(5,bb3d);
   SetIndexBuffer(6,bb4u);
   SetIndexBuffer(7,bb4d);
   
      indicatorFileName = WindowExpertName();
      returnBars        = (TimeFrame1==-99); if (returnBars)     return(0);
      calculateValue    = (TimeFrame1==-98); if (calculateValue) return(0);
      
      //
      //
      //
      //
      //
      
      for (int i=0; i<8; i++) 
      {
         SetIndexStyle(i,DRAW_ARROW,EMPTY,LinesWidth,i%2==0?ColorUp:ColorDown); SetIndexArrow(i,110); 
      }
      timeFrames[0] = timeFrameValue(TimeFrame1);
      timeFrames[1] = timeFrameValue(TimeFrame2);
      timeFrames[2] = timeFrameValue(TimeFrame3);
      timeFrames[3] = timeFrameValue(TimeFrame4);
      alertsLevel = fmin(fmax(alertsLevel,3),4);
      IndicatorShortName(UniqueID);
   return(0);
}
int deinit() { ObjectsDeleteAll(0,UniqueID); return(0); }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double trend[][2];
#define _up 0
#define _dn 1
int start()
{
   int i,r,counted_bars=IndicatorCounted();
      if(counted_bars < 0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { bb1u[0] = limit+1; return(0); }
         if (calculateValue) { calculateByBB(limit); return(0); }

         if (timeFrames[0] != _Period) limit = (int)fmax(limit,fmin(Bars-1,iCustom(NULL,timeFrames[0],indicatorFileName,-99,0,0)*timeFrames[0]/_Period));
         if (timeFrames[1] != _Period) limit = (int)fmax(limit,fmin(Bars-1,iCustom(NULL,timeFrames[1],indicatorFileName,-99,0,0)*timeFrames[1]/_Period));
         if (timeFrames[2] != _Period) limit = (int)fmax(limit,fmin(Bars-1,iCustom(NULL,timeFrames[2],indicatorFileName,-99,0,0)*timeFrames[2]/_Period));
         if (timeFrames[3] != _Period) limit = (int)fmax(limit,fmin(Bars-1,iCustom(NULL,timeFrames[3],indicatorFileName,-99,0,0)*timeFrames[3]/_Period));
         if (ArrayRange(trend,0)!=Bars) ArrayResize(trend,Bars);


         //
         //
         //
         //
         //
         
         bool initialized = false;
         if (!initialized)
         {
            initialized = true;
            int window = WindowFind(UniqueID);
            for (int t=0; t<4; t++)
            {
               string label = timeFrameToString(timeFrames[t]);
               ObjectCreate(UniqueID+(string)t,OBJ_TEXT,window,0,0);
                  ObjectSet(UniqueID+(string)t,OBJPROP_COLOR,LabelsColor);
                  ObjectSet(UniqueID+(string)t,OBJPROP_PRICE1,t+LabelsVerticalShift);
                  ObjectSetText(UniqueID+(string)t,label,8,"Arial");
            }               
         }
         for (int t=0; t<4; t++) ObjectSet(UniqueID+(string)t,OBJPROP_TIME1,Time[0]+Period()*LabelsHorizontalShift*60);

   //
   //
   //
   //
   //
   
   for(i = limit, r=Bars-i-1; i >= 0; i--,r++)
   {
      trend[r][_up] = 0;
      trend[r][_dn] = 0;
      for (int k=0; k<4; k++)
      {
         int y = iBarShift(NULL,timeFrames[k],Time[i]);
            double bb1 = iCustom(NULL,timeFrames[k],indicatorFileName,-98,0,0,0,SlowLength,SlowPipDisplace,FastLength,FastPipDisplace,2,y);
            double bb2 = iCustom(NULL,timeFrames[k],indicatorFileName,-98,0,0,0,SlowLength,SlowPipDisplace,FastLength,FastPipDisplace,3,y);
            bool   isUp  = (bb1<bb2);
          
            switch (k)
            {
               case 0 : if (isUp) { bb1u[i] = k+1; bb1d[i] = EMPTY_VALUE;}  else { bb1d[i] = k+1; bb1u[i] = EMPTY_VALUE; } break;
               case 1 : if (isUp) { bb2u[i] = k+1; bb2d[i] = EMPTY_VALUE;}  else { bb2d[i] = k+1; bb2u[i] = EMPTY_VALUE; } break;
               case 2 : if (isUp) { bb3u[i] = k+1; bb3d[i] = EMPTY_VALUE;}  else { bb3d[i] = k+1; bb3u[i] = EMPTY_VALUE; } break;
               case 3 : if (isUp) { bb4u[i] = k+1; bb4d[i] = EMPTY_VALUE;}  else { bb4d[i] = k+1; bb4u[i] = EMPTY_VALUE; } break;
            }
            if (isUp)
                  trend[r][_up] += 1;
            else  trend[r][_dn] += 1;
      }
   }
   manageAlerts();
   return(0);
}


//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void calculateByBB(int limit)
{
   for (int i=limit; i>=0; i--) 
   {
       double pipMultiplier = _Point*MathPow(10,Digits%2);
       double thigh1 = High[iHighest(NULL, 0, MODE_HIGH,SlowLength,i)] + SlowPipDisplace*pipMultiplier;
       double tlow1  = Low[iLowest(NULL,   0, MODE_LOW, SlowLength,i)] - SlowPipDisplace*pipMultiplier;
       double thigh2 = High[iHighest(NULL, 0, MODE_HIGH,FastLength,i)] + FastPipDisplace*pipMultiplier;
       double tlow2  = Low[iLowest(NULL,   0, MODE_LOW, FastLength,i)] - FastPipDisplace*pipMultiplier;
       if (i<Bars-1 && Close[i]>bb1u[i+1])  // line1 = bb1u
             bb1u[i] = tlow1;
       else  bb1u[i] = thigh1;             
       if (i<Bars-1 && Close[i]>bb1d[i+1])  // line2 = bb1d
             bb1d[i] = tlow2;
       else  bb1d[i] = thigh2;             
            
       //
       //
       //
       //
       //
            
       bb2d[i] = EMPTY_VALUE;              // hist1 = bb2d
       bb2u[i] = EMPTY_VALUE;              // hist2 = bb2u
       bb3u[i] = i<Bars-1 ? bb3u[i+1] : 0; // bb3u = trena
       bb4u[i] = 0;                         //bb4u = trend
         if (Close[i]<bb1u[i] && Close[i]<bb1d[i]) bb4u[i] =  1;
         if (Close[i]>bb1u[i] && Close[i]>bb1d[i]) bb4u[i] = -1;
         if (bb1u[i]>bb1d[i] || bb4u[i] ==  1)     bb3u[i] =  1;
         if (bb1u[i]<bb1d[i] || bb4u[i] == -1)     bb3u[i] = -1;
         if (bb3u[i]== 1) bb2d[i] = 1;
         if (bb3u[i]==-1) bb2u[i] = 1;        

      }
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = Bars-1;
      if (trend[whichBar][_up] >= alertsLevel || trend[whichBar][_dn] >= alertsLevel)
      {
         if (trend[whichBar][_up] >= alertsLevel) doAlert("up"  ,(int)trend[whichBar][_up]);
         if (trend[whichBar][_dn] >= alertsLevel) doAlert("down",(int)trend[whichBar][_dn]);
      }
   }
}

//
//
//
//
//

void doAlert(string doWhat, int howMany)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[0]) {
       previousAlert  = doWhat;
       previousTime   = Time[0];

       //
       //
       //
       //
       //

       message =  Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" "+(string)howMany+" time frames of ptl are aligned "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(Symbol()+" 4 time frame ptl ",message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//
//
//
//
//

int timeFrameValue(int _tf)
{
   int add  = (_tf>=0) ? 0 : MathAbs(_tf);
   if (add != 0) _tf = _Period;
   int size = ArraySize(iTfTable); 
      int i =0; for (;i<size; i++) if (iTfTable[i]==_tf) break;
                                   if (i==size) return(_Period);
                                                return(iTfTable[(int)MathMin(i+add,size-1)]);
}
string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}
    
